package org.simpatia.service.heartbeat;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.simpatia.Context;
import org.simpatia.Module;
import org.simpatia.Service;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

public class HeartbeatServiceImpl implements Service<HeartbeatServiceConfiguration, Void> {
    private Thread sender;
    private final AtomicBoolean active = new AtomicBoolean();

    public void activate(String name, final HeartbeatServiceConfiguration configuration, Context context) {
        active.set(true);
        sender = new Thread() {
            public void run() {
                while(active.get()) {
                    HttpClient client = new HttpClient();
                    HttpMethod method = new GetMethod(configuration.getEndpoint());
                    try {
                        client.executeMethod(method);
                    } catch (IOException e) { }

                    try {
                        Thread.sleep(configuration.getIntervalMs());
                    } catch (InterruptedException e) {}
                }
            }
        };
        sender.start();
    }

    public void destroy() {
        active.set(false);
    }

    public Void getRESTInterface() {
        return null;
    }

    public void registerService(String serviceName, Module module) {
    }

    public void unregisterService(String serviceName) {
    }
}
